module.exports = core;

const path = require('path');
const dotenv = require('dotenv')
const commander = require('commander')
const semver = require('semver')

 
var colors = require('colors/safe');
const { homedir } = require('os')
const pathExistsSync = require('path-exists').sync

const pkg = require('../package.json')
const log = require('@imooc-my-test1/log')
const init = require('@imooc-my-test1/init')
const exec = require('@imooc-my-test1/exec')


const { getOnLineLatestVersion } = require('@imooc-my-test1/get-npm-info')

const constant= require('./const')

let args = [];
let userHome = undefined;
const program = new commander.Command();

async function core(args) {
  try {
    await prepare()
    registCommander()
  } catch (error) {
    log.error(colors.red(error.message))
  }

}

async function prepare() {
  checkPkgVersion()
  checkRoot()
  checkUserHome()
  checkEnv()
  await checkGlobalUpdate()
}

function registCommander() {
  program
    .name(Object.keys(pkg.bin)[0])
    .version(pkg.version, '-v, -V, --veriosion', '显示版本号')
    // 这里要用尖括号表示有值
    .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径')
    .option('-d, --debug', '开启debugger模式', false)
    .usage('<command> [option]')

  program
    .command('init [projectName]')
    .description('初始化项目')
    .option('-f, --force', '强制初始化')
    .action(exec)

  program.on('option:debug', () => {
    const args = program.opts();
    if(args.debug) {
      process.env.LOG_LEVEL = 'verbose'
    } else {
      process.env.LOG_LEVEL = 'info'
    }
    // 直接修改level可以修改log的等级模式
    log.level = process.env.LOG_LEVEL;
    log.verbose('debug', 'debug start')
  })

  program.on('command:*', (obj) => {
    const availableCommands = program.commands.map((cmd) => cmd.name());
    console.log(colors.red(`未知的命令：${obj[0]}`))
    if( availableCommands.length > 0 ) {
      console.log(colors.green(`可用命令：${availableCommands.join(',')}`))
    }
  })

  program.on('option:targetPath', function(obj) {
    const args = program.opts()
    // 这里使用全局的cli进行传递参数
    process.env.CLI_TARGET_PATH = args.targetPath;

  })

  program.parse()
}

async function checkGlobalUpdate() {
  // 1. 获取当前版本号和模块号
  // 2. 获取线上所有的版本号
  // 3. 比对那些版本号是大于当前版本号
  // 4. 获取最新版本号，提示用户更新到最新版本
  const currentVersion = pkg.version;
  const pkgName = pkg.name;
  const lastVersion = await getOnLineLatestVersion(currentVersion, pkgName)
  if(lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      'update',
      colors.yellow(
        [
          `请手动更新 ${pkgName}，当前版本：${currentVersion}，最新版本：${lastVersion}`,
          `更新命令 npm install ${pkgName}`
        ].join('\n')
      )
    );
  }
}

function checkEnv() {
  const dotenv = require('dotenv');
  const dorenvPath = path.resolve(userHome, '.dg-env')
  let config;
  if(pathExistsSync(dorenvPath)) {
    config = dotenv.config({path: dorenvPath}).parsed;
  } else {
    config = createDefaultConfig()
  }
  log.verbose('env', config)
}

function createDefaultConfig() {
  const cliConfig = {
    home: userHome
  };
  cliConfig['cliHome'] = path.join(
    userHome,
    process.env.CLI_HOME_PATH || constant.DEFAULT_CLI_HOME
  )
  process.env.CLI_HOME_PATH = cliConfig.cliHome;
  return cliConfig
}

function checkUserHome() {
   userHome = homedir();
  if (!userHome || !pathExistsSync(userHome)) {
    throw new Error(colors.red('当前用户主目录不存在！'));
  }
}

function checkRoot() {
  // process.geteuid() 获取当前登录人是否为管理员
  const rootCheck = require('root-check')
  rootCheck();
}

// 检查当前包版本
function checkPkgVersion() {
  const version = pkg.version;
  log.success('cli', `checked version ${version}`)
}

